# -*- coding: utf-8 -*-
from django.utils.safestring import mark_safe

class Pagination():
	def __init__(self, all_data_num, page=1, per_page_num=10, max_show_page=11):
		# 类型转换和异常处理
		try:
			page = int(page)
			if page <= 0:
				page = 1
		except Exception:
			page = 1

		# 总页数
		all_page_num, more = divmod(all_data_num, per_page_num)
		if more:
			all_page_num += 1

		if all_page_num < max_show_page:
			max_show_page = all_page_num

		# 如果page大于总页数
		if page > all_page_num:
			page = all_page_num

		# 切片实现分页
		# 第一页 0 10
		# 第二页 10 20
		# 第三页 20 30
		# 总数据量为0
		if all_data_num == 0:
			self.start = 0
			self.end = 0
		else:
			self.start = (page - 1) * per_page_num
			self.end = page * per_page_num

		# 对称显示当前页
		half_show = max_show_page // 2
		if page <= half_show:
			start_page = 1
			end_page = max_show_page
		elif page > all_page_num - half_show:
			start_page = all_page_num - half_show
			end_page = all_page_num
		else:
			start_page = page - half_show
			end_page = page + half_show

		self.page = page  # 当前页
		self.all_data_num = all_data_num  # 数据总条数
		self.per_page_num = per_page_num  # 每页显示的条数
		self.max_show_page = max_show_page  # 最多显示的总页数
		self.all_page_num = all_page_num  # 总页数
		self.start_page = start_page  # 开始显示的页
		self.end_page = end_page  # 最后显示的页

	@property
	def page_html(self):
		page_list = []
		page_html = '<nav><ul class="pagination">'
		# 如果当前页为1，首页就显示禁用状态
		if self.page == 1:
			page_html += '<li class="disabled"><a>首页</a></li>'
		else:
			page_html += '<li><a href="?page=1">首页</a></li>'
		# 如果当前页为1，上一页就显示禁用状态
		if self.page == 1:
			page_html += '<li class="disabled"><a>上一页</a></li>'
		else:
			page_html += '<li><a href="?page={}">上一页</a></li>'.format(self.page - 1)

		for i in range(self.start_page, self.end_page + 1):
			if i == self.page:
				page_li_html = '<li class="active"><a href="?page={}">{}</a></li>'.format(i, i)
			else:
				page_li_html = '<li><a href="?page={}">{}</a></li>'.format(i, i)
			page_list.append(page_li_html)
		page_html += ''.join(page_list)

		# 如果当前页是尾页，下一页显示禁用状态
		if self.page == self.all_page_num:
			page_html += '<li class="disabled"><a>下一页</a></li>'
		else:
			page_html += '<li><a href="?page={}">下一页</a></li>'.format(self.page + 1)

		# 如果当前页是尾页，尾页显示禁用状态
		if self.page == self.all_page_num:
			page_html += '<li class="disabled"><a>尾页</a></li><li><a>共{}条</a></li></ul></nav>'.format(self.all_data_num)
		else:
			page_html += '<li><a href="?page={}">尾页</a></li><li><a>共{}条</a></li></ul></nav>'.format(self.all_page_num, self.all_data_num)
		return mark_safe(page_html)